<?php

/**
 * This is the model class for table "{{facebook_user}}".
 *
 * The followings are the available columns in table '{{facebook_user}}':
 * @property string $id
 * @property integer $user_id
 * @property string $facebook_id
 *
 * The followings are the available model relations:
 * @property User $user
 */
class FacebookUser extends HActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return FacebookUser the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{facebook_user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id', 'numerical', 'integerOnly'=>true),
			array('facebook_id', 'length', 'max'=>32),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, user_id, facebook_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'user_id' => 'User',
			'facebook_id' => 'Facebook',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('facebook_id',$this->facebook_id,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * This method is used to sync facebook user and throwbook user
	 *
	 * @return	User
	 */
	public function syncUser()
	{
		$fbUserinfo = Yii::app()->facebook->getInfo();
		if ($fbUserinfo) {
			Yii::import('application.modules.user.models.User');
			$user = new User;
			$user->username = 'fid'.$fbUserinfo['id'];
			$user->encryptPassword('fid'.$fbUserinfo['id']);
			$user->email = $fbUserinfo['email'];
			$user->createtime = time();
			$user->status = User::STATUS_NOACTIVE;
			$modelTransaction = $user->dbConnection->beginTransaction(); // Transaction for model begin
			try {
				if (!$user->save()) throw new Exception('Cannot save to model User.');
				
				Yii::import('application.modules.user.models.UserProfiles');
				$profiles = new UserProfiles;
				$profiles->user_id = $user->id;
				$profiles->firstname = $fbUserinfo['first_name'];
				$profiles->lastname = $fbUserinfo['last_name'];
				if (!$profiles->save()) throw new Exception('Cannot save to model UserProfiles.');
				
				$className = __CLASS__;
				$fbuser = new $className;
				$fbuser->user_id = $user->id;
				$fbuser->facebook_id = $fbUserinfo['id'];
				if (!$fbuser->save()) throw new Exception('Cannot save to model FacebookUser.');
				
				$modelTransaction->commit(); // Commit transaction
				return $user;
			} catch(Exception $e) {
				$modelTransaction->rollBack(); // Roll back transaction
				return null;
			}
		}
	}
	
	/**
	 * This method is used to sync facebook user info and throwbook user
	 */
	public function syncUserInfo()
	{
		$fbUserinfo = Yii::app()->facebook->getInfo();
		if ($fbUserinfo) {
			Yii::import('application.modules.user.models.User');
			Yii::import('application.modules.user.models.UserProfiles');
			Yii::import('application.modules.textbooks.models.TextbookUserUniversity');
			Yii::import('application.modules.textbooks.models.TextbookUniversity');
			$profiles = $this->user->profiles;
			$profiles->firstname = isset($fbUserinfo['first_name']) ? $fbUserinfo['first_name'] : '';
			$profiles->middlename = isset($fbUserinfo['middle_name']) ? $fbUserinfo['middle_name'] : '';
			$profiles->lastname = isset($fbUserinfo['last_name']) ? $fbUserinfo['last_name'] : '';
			$profiles->gender = isset($fbUserinfo['gender']) ? ($fbUserinfo['gender']=='male'?1:0) : 0;
			
			// if (isset($fbUserinfo['education']))
				// foreach ($fbUserinfo['education'] as $edu)
					// if ($edu['type'] == 'College') {
						// $university = TextbookUniversity::model()->findByAttributes(array('name'=>$edu['school']['name']));
						// if (!$university) {
							// $university = new TextbookUniversity;
							// $university->name = $edu['school']['name'];
							// $university->fbid = $edu['school']['id'];
							// $university->save();
						// }
						// if ($university) {
							// $userUniversity = TextbookUserUniversity::model()->countByAttributes(array(
								// 'user_id' => $profiles->user_id,
								// 'university_id' => $university->id,
							// ));
							// if (!$userUniversity) {
								// $userUniversity = new TextbookUserUniversity;
								// $userUniversity->user_id = $profiles->user_id;
								// $userUniversity->university_id = $university->id;
								// $userUniversity->save();
							// }
						// }
					// }
			
			$this->last_sync = time();
			return ($profiles->save() && $this->save());
		}
		
		return false;
	}
}